package com.intelligent.system.auth.controller;

import com.intelligent.system.auth.uitls.OAuth2CertUtils;
import com.intelligent.system.common.response.ResultDO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/token")
public class TokenController {

    private static final String TOKEN_PREFIX = "token:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private OAuth2CertUtils oAuth2CertUtils;

    @GetMapping("/parse")
    public ResultDO<Map<String, Object>> parseToken(@RequestParam String token) {
        try {
            log.info("正在尝试解析token");
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(oAuth2CertUtils.getPublicKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            Map<String, Object> response = new HashMap<>(claims);
            log.info("成功解析token，用户ID: {}", claims.getSubject());
            return ResultDO.success(response);
        } catch (Exception e) {
            log.error("解析token失败: {}", e.getMessage());
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Invalid token: " + e.getMessage());
            return ResultDO.error(0, "");
        }
    }

    @GetMapping("/get/{userId}")
    public ResultDO<String> getToken(@PathVariable String userId) {
        String token;
        try {
            log.info("正在尝试从Redis获取用户 {} 的token", userId);
            token = redisTemplate.opsForValue().get(TOKEN_PREFIX + userId);
        } catch (Exception e) {
            log.error("从Redis获取用户 {} 的token失败: {}", userId, e.getMessage());
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to retrieve token: " + e.getMessage());
            return ResultDO.error(0,"");
        }

        return ResultDO.success(token);
    }
} 